const fs = require("fs");

function renameSuffix({ dir, suffix, mode }) {
  //校验目录是否存在
  if (!fs.existsSync(dir)) {
    return {
      msg: "目录不存在",
      data: [],
    };
  }

  let newList = [];
  const files = fs.readdirSync(dir);
  files.forEach((v) => {
    //文件获取后缀
    var oldSuffix = v.substring(v.lastIndexOf("."));
    //原文件名路径
    var oldName = dir + "/" + v;
    //替换文件名称后缀 获取新路径
    var newName = dir + "/" + v.replace(oldSuffix, suffix);

    newList.push({
      oldName: v,
      newName: newName,
    });

    if (mode === "rename") {
      try {
        fs.renameSync(oldName, newName);
      } catch (renameErr) {
        console.error(`重命名文件失败 ${oldName}:`, renameErr);
      }
    }
  });
  return {
    msg: mode === "rename" ? "重命名成功" : "预览模式",
    data: newList,
  };
}
module.exports = renameSuffix;
